import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from '../store';
import format from '../../../../utils/formatJson';

import { Button, Modal, Form, Input, Select } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;

const typeList=[
  {key: 1, value: 1, text: 'number'},
  {key: 2, value: 2, text: 'String'},
  {key: 3, value: 3, text: 'Date'},
  {key: 4, value: 4, text: 'boolean'},
  {key: 5, value: 5, text: 'integer'},
  {key: 6, value: 6, text: 'bigNumber'},
  {key: 7, value: 7, text: 'serializable'},
  {key: 8, value: 8, text: 'binary'},
  {key: 9, value: 9, text: 'timestamp'},
  {key: 10, value: 10, text: 'inet'},
];
const delList=[
  {key: 0, value: 0, text: '不去除'},
  {key: 1, value: 1, text: '去除左空格'},
  {key: 2, value: 2, text: '去除右空格'},
  {key: 3, value: 3, text: '去除左右空格'},
];

// const layout = {
//   labelCol: {
//     span: 4,
//   },
//   wrapperCol: {
//     span: 20,
//   },
// };

class CreateConnection extends Component{
  state={
    visible: false,
  };

  handleClick = () => {
    this.setState({visible:true})
  };

  handleOk = (values) => {
    let configName = values.configName;
    let description = "";
    let url = values.url;
    let method = values.method;
    let data = {url,method};
    let fieldData = values.fields?JSON.stringify(values.fields):"[]";
    let username = "admin";//待修改
    let params = {configName,description,data,fieldData,username};
    this.props.saveCon(params,this.props.searchValue);
    this.props.clearPreview();
    this.setState({visible:false});
  };

  handleCancel = () => {
    this.setState({visible:false});
    this.props.clearPreview();
    this.formRef.current.resetFields();
  };

  componentDidMount(){
  };

  testCon = () => {
    this.formRef.current.validateFields(["url","method"])
      .then(values => {
        let url = values.url;
        let method = values.method;
        let data = {url,method}
        this.props.testCon(data);
      })
  }

  formRef = React.createRef();
  render(){
    return (
      <Fragment>
        <Button type="primary" style={{marginLeft: 24}} onClick={this.handleClick}>新建</Button>
        <Modal
          title="新建接口"
          visible={this.state.visible}
          //bodyStyle={{ padding: '12px 24px' }}
          onOk={() => {
            this.formRef.current
              .validateFields()
              .then(values => {
                this.formRef.current.resetFields();
                this.handleOk(values);
              })
              .catch(info => {
                console.log('Validate Failed:', info);
              });
          }}
          onCancel={this.handleCancel}
          okText="确认"
          cancelText="取消"
        >
          <Form
            //{...layout}
            name="basic"
            ref={this.formRef}
          >
            <Form.Item
            label="接口名称"
            name="configName"
            rules={[
              {
                required: true,
                message: '请输入接口名称！',
              },]}>
              <Input placeholder="请输入接口名称"/>
            </Form.Item>
            <Form.Item
            label="URL"
            name="url"
            rules={[
              {
                required: true,
                message: '请输入URL！',
              },]}>
              <Input placeholder="请输入URL"/>
            </Form.Item>
            <Form.Item
            label="请求类型"
            name="method"
            rules={[
              {
                required: true,
                message: '请选择请求类型！',
              },]}>
              <Select placeholder="请选择请求类型">
                <Option value="GET">GET</Option>
                <Option value="POST">POST</Option>
              </Select>
            </Form.Item>
            <Form.List name="fields">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map((field, index) => (
                    <div key={field.key} style={{backgroundColor:'#f0f2f5', padding:8, marginTop:12}}>
                      <div>
                        <span style={{fontWeight:'bold'}}>字段{index+1}</span>
                        <MinusCircleOutlined
                        className="dynamic-delete-button"
                        style={{ margin: '0 8px' }}
                        onClick={() => {
                          remove(field.name);
                        }}
                        />
                      </div>
                      <Form.Item
                      label="名称"
                      name={[field.name, "fieldName"]}
                      fieldKey={[field.fieldKey, "fieldName"]}
                      rules={[
                        {
                          required: true,
                          message: '请输入字段名称！',
                        },]}>
                        <Input placeholder="请输入字段名称"/>
                      </Form.Item>
                      <Form.Item
                      label="路径"
                      name={[field.name, "path"]}
                      fieldKey={[field.fieldKey, "path"]}
                      rules={[
                        {
                          required: true,
                          message: '请输入路径！',
                        },]}>
                        <Input placeholder="请输入路径"/>
                      </Form.Item>
                      <Form.Item
                      label="字段类型"
                      name={[field.name, "type"]}
                      fieldKey={[field.fieldKey, "type"]}
                      rules={[
                        {
                          required: true,
                          message: '请选择字段类型！',
                        },]}>
                        <Select placeholder="请选择字段类型">
                        {typeList.map(item => (
                          <Option key={item.key} value={item.value} title={item.text}>{item.text}</Option>
                        ))}
                        </Select>
                      </Form.Item>
                      <Form.Item
                      label="去除空格"
                      name={[field.name, "trimType"]}
                      fieldKey={[field.fieldKey, "trimType"]}
                      rules={[
                        {
                          required: true,
                          message: '请选择去除空格类型！',
                        },]}>
                        <Select placeholder="请选择去除空格类型">
                        {delList.map(item => (
                          <Option key={item.key} value={item.value} title={item.text}>{item.text}</Option>
                        ))}
                        </Select>
                      </Form.Item>
                    </div>
                  ))}
                <Form.Item noStyle>
                  <Button
                    style={{margin:"8px 0"}}
                    type="dashed"
                    onClick={() => {
                      add();
                    }}
                  >
                    新增字段
                  </Button>
                </Form.Item>
              </div>
              );
            }}
            </Form.List>
            <Button type="primary" onClick={this.testCon} style={{marginBottom:8}}>数据预览</Button>
            <Form.Item >
              <Input.TextArea rows={8} value={format(this.props.preview)}/>
            </Form.Item>
          </Form>
        </Modal>
      </Fragment>    
    );
  }
}

const mapStateToProps = (state) => {
  return {
    preview: state.getIn(['api','preview']),
  }
}

const mapDispatchToProps = (dispatch) => ({
  testCon(data){//测试连接
    dispatch(actionCreators.testConOperation(data));
  },
  saveCon(params,searchValue){
    dispatch(actionCreators.saveConOperation(params,searchValue));
  },
  clearPreview(){
    dispatch(actionCreators.clearPreviewOperation());
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(CreateConnection);